import {
  getStandFileInfoByPage,
  addStandFileInfo,
  uploadStandFileInfo,
  delStandFileInfo,
  exportStandFileInfo,
  getProductTypeList,
  getStandFileType,
  downloadFile,
} from '@/services/design/standFileInfo';
import { PlusOutlined, UploadOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Select, Upload, Descriptions } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
const StandFileInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const [file, setFile] = useState();
  const [category, setcategory] = useState();
  const [optionsTypeDesc, setoptionsTypeDesc] = useState([]); //下拉框用到
  const [optionsstandfile, setoptionsstandfile] = useState([]);

  const [form] = Form.useForm();
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '柜体类型',
      dataIndex: 'standTypeDesc',
    },
    {
      title: '柜体编号',
      dataIndex: 'standTypeCode',
    },
    {
      title: '文件类别',
      dataIndex: 'category',
    },
    {
      title: '文件编号',
      dataIndex: 'fileCode',
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
    },

    {
      title: '文件后缀',
      dataIndex: 'fileExtEndDate',
    },

    {
      title: '文件大小',
      dataIndex: 'fileSize',
    },
    {
      title: '备注',
      dataIndex: 'memo',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="downloadKey"
          onClick={() => {
            downloadFile({ fileCode: record.fileCode }).then((res) => {
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              aLink.setAttribute('download', `${record.fileName}`);
              aLink.click();
              document.body.removeChild(aLink);
            });
          }}
        >
          下载
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delStandFileInfo({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '上传附件') {
      form
        .validateFields()
        .then(async () => {
          const res = {
            ...form.getFieldsValue(),
            standTypeCode: history.location.state.standTypeCode,
            standTypeDesc: history.location.state.standTypeDesc,
          };
          const formData = new window.FormData();
          formData.append('file', file);
          res.file = formData;
          const result = await uploadStandFileInfo(res);
          if (result != null) {
            message.success('添加成功');
            form.resetFields();
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  const getproductInfo = async () => {
    // 获取文件类型
    const gettype = await getStandFileType(null);
    const productfiletype: any[] = [];
    gettype.data.map((item: any, index: any) => {
      productfiletype.push({ value: item, label: item });
    });
    setoptionsstandfile(productfiletype);
  };

  const onFilesChange = async (file) => {
    setFile(file);
  };

  const beforeUpload = (file) => {
    setFile(file);
    return false;
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="标准柜体附件信息查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<ArrowLeftOutlined />}
            onClick={() => {
              history.push('/design/standProduct');
            }}
            type="primary"
          >
            返回
          </Button>,
          <Button
            key="button"
            icon={<UploadOutlined />}
            onClick={() => {
              setCreateOrUpdate(true);
              setFormTitle('上传附件');
              setModalVisit(true);
            }}
            type="primary"
          >
            上传
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params, standTypeCode: history.location.state.standTypeCode };
          const sorters = sortTran(sort);
          const filters = filterTran(res);
          const result = await getStandFileInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          getproductInfo();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 2000, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="柜体类型"
            name="standTypeDesc"
            rules={[{ required: true, message: '请选择柜体类型!' }]}
          >
             <Select
              placeholder="请选择柜体类型"
              disabled  //不可更改
              onChange={(value, label) => {  }}
              options={optionsTypeDesc}
            />
          </Form.Item>
          <Form.Item
            label="柜体编号"
            name="standTypeCode"
            rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
          >
            <Input disabled/>
          </Form.Item> */}
          <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别!' }]}
          >
            <Select
              placeholder="请选择文件类别"
              onChange={(value, label) => {}}
              options={optionsstandfile}
            />
          </Form.Item>
          <Form.Item label="" name="file" rules={[{ required: true, message: '请上传文件!' }]}>
            {/* <div key={Math.random()}> */}
            <Upload
              file-list="fileList"
              // getValueFromEvent={normFile}
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
            {/* </div> */}
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default StandFileInfo;
